# Create your views here.
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse, HttpResponseNotFound
from django.utils import simplejson
from models import RegistrationProfile,TestInfo
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required

@login_required
def load_medical_record(request, extra_context = None):
    try:
        user_profile = RegistrationProfile.objects.get(user = request.user)
    except User.DoesNotExist:
        resp = dict(success=False, errors="No user profile of user %s" % request.user.username)
        return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder)) 
    except:
        import traceback
        print repr(traceback.print_exc())
        resp = dict(success=False, errors="Server Error")
        return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
    else:
        resp = dict(success=True, data=dict(medical_record=user_profile.medical_record))
        return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
    

@login_required
def save_medical_record(request, extra_context = None):
    if request.method == "POST":
        try:
            user_profile = RegistrationProfile.objects.get(user = request.user)
        except User.DoesNotExist:
            resp = dict(success=False, errors="No user profile of user %s" % request.user.username)
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder)) 
        except:
            import traceback
            print repr(traceback.print_exc())
            resp = dict(success=False, errors="Server Error")
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
        else:
            user_profile.medical_record = request.POST['medical_record']
            user_profile.save()
            resp = dict(success=True)
            return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
    else:
        return HttpResponseNotFound('<h1>Can not go to this view unless with method other than  POST </h1>')
    

@login_required
def load_test_info(request, extra_context = None):
    try:
        user_profile = RegistrationProfile.objects.get(user = request.user)        
        all_test_info = TestInfo.objects.filter(user = user_profile).order_by(request.REQUEST.get("sort") if request.REQUEST.get("dir") != 'DESC' else '-' + request.REQUEST.get("sort"))
    except User.DoesNotExist:
        resp = dict(success=False, errors="NO user profile of user %s" % request.user.username)
        return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder)) 
    except:
        import traceback
        print repr(traceback.print_exc())
        resp = dict(success=False, errors="Server Error")
        return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))
    else:
        startIndex = int(request.REQUEST.get('start',0))
        endIndex = startIndex + int(request.REQUEST.get('limit', 25))
        paged_test_info = all_test_info[startIndex:endIndex]
        resp = dict(success=True, totalCount=len(all_test_info), \
                    data=[dict(content=test.content, date=test.date, order_by_doctor=test.order_by_doctor, test_id = test.id) for test in paged_test_info])
        return HttpResponse(simplejson.dumps(resp, cls=DjangoJSONEncoder))